<template>
<div id="set-avatar">
  <div class="over-avatar" data-text="更换头像" @click="toggleShow">
    <img :src="imgUrl ? imgUrl : 'static/timg.jpg'" alt="个人头像" >
  </div>

  <my-upload field="img" @crop-success="cropSuccess" v-model="show" :width="100" :height="100" img-format="png"></my-upload>
  <!-- <img :src="imgDataUrl"> -->
</div>
</template>

<script>
import myUpload from 'vue-image-crop-upload'
import axios from 'axios'

export default {
  data() {
    return {
      show: false
    }
  },
  props: {
    imgUrl: {
      type: String
    }
  },
  methods: {
    toggleShow() {
      this.show = !this.show
    },
    cropSuccess(imgDataUrl, field) {
      var formData = new FormData()
      formData.append('file', this.convertBase64UrlToBlob(imgDataUrl))
      axios({
        url: 'file/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        this.$emit('upload-success', res.data.data.url)
      }).catch((e) => {
        console.log('error--->', e)
      })
    },
    convertBase64UrlToBlob(urlData) {
      var bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte

      // 处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length)
      var ia = new Uint8Array(ab)
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      let blob = new Blob([ab], {
        type: 'image/png'
      })
      return new File([blob], 'avatar.png')
    }
  },
  components: {
    'my-upload': myUpload
  }
}
</script>

<style lang="scss">
.over-avatar {
    display: inline-block;
    position: relative;
    &::after {
        position: absolute;
        left: 0;
        top: 0;
        cursor: pointer;
        width: 100%;
        height: 100%;
        line-height: 100px;
        text-align: center;
        border-radius: 10px;
        background-color: rgba(0, 0, 0, 0.5);
        content: attr(data-text);
        transition: all 1s ease;
        transform: translateY(-100%);
        color: #FFF;
    }
    &:hover {
        &::after {
            transform: translateY(0);
        }
    }
    > img {
        width: 100px;
        border-radius: 10px;
        &:hover {
            ::after {
                content: '更换头像';
                background: #000000;
            }
        }
    }
}
</style>
